<template>
  <van-nav-bar title="收货地址" left-arrow @click-left="onBack" />

  <van-address-list v-model="AddressId" :list="AddressList" default-tag-text="默认" @add="onAdd" @edit="onEdit" @select="onSelect" />
</template>
<script>
  import { showNotify } from 'vant'
  export default {
    data() {
      return {
        AddressId: 0, // 选择地址
        AddressList: [], // 收货地址数据
        LoginAuth: {},
      }
    },
    created() {
      this.LoginAuth = this.$cookies.get('LoginAuth') ? this.$cookies.get('LoginAuth') : {}
      this.getAddressData()
    },
    methods: {
      onAdd() {
        this.$router.push('/business/address/add')
      },
      onEdit(item) {
        this.$router.push({ path: '/business/address/edit', query: { addrid: item.id } })
      },
      onBack() {
        if (this.$route.query.action == 'order') {
          this.$router.go(-1)
        } else {
          this.$router.go(-1)
        }
      },
      async getAddressData() {
        let result = await this.$api.AddressIndex({ busid: this.LoginAuth.id })

        if (result.code === 0) {
          showNotify({
            type: 'warning',
            duration: 1500,
            message: result.msg,
          })
        }

        let data = []

        for (let item of result.data) {
          if (item.status == 1) {
            this.AddressId = item.id
          }

          data.push({
            id: item.id,
            name: item.consignee,
            tel: item.mobile,
            address: item.region_text + ' ' + item.address,
            isDefault: item.status == 1 ? true : false,
          })
        }

        this.AddressList = data

        if (this.$route.query.action == 'order') {
          let address = this.$cookies.get('address') ? this.$cookies.get('address') : ''

          if (address) {
            this.AddressId = address.id
          }
        }
      },
      async onSelect(info) {
        if (this.$route.query.action == 'order') {
          let data = {
            id: info.id,
            consignee: info.name,
            mobile: info.tel,
          }

          this.$cookies.set('address', data)

          this.$router.go(-1)
        } else {
          let data = {
            addrid: info.id,
            busid: this.LoginAuth.id,
          }

          let result = await this.$api.AddressSelect(data)

          if (result.code === 1) {
            this.getAddressData()
          } else {
            showNotify({
              type: 'warning',
              message: result.msg,
              duration: 1500,
            })
          }
        }
      },
    },
  }
</script>
